#region

using System;
using System.IO;
using System.Reflection;
using System.Resources;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Xml;
using AreaBuilder.Properties;

#endregion

namespace AreaBuilder {
    public static class Funcs {
        private static readonly ResourceManager resources = new ResourceManager(typeof(Resources));
        private static readonly XmlDocument doc = new XmlDocument();
        private static readonly String confContents = (String)resources.GetObject("types");
        private static bool reCheck;

        public static String getXPath(String path) {
            if (doc.FirstChild == null)
                doc.LoadXml(confContents);

            var output = new StringBuilder("");
            var nav = doc.CreateNavigator();
            var expr = nav.Compile(path);
            var iterator = nav.Select(expr);

            try {
                while (iterator.MoveNext()) {
                    output.Append(iterator.Current.Clone().Value);
                    output.Append("|");
                }
            } catch (Exception) {
            }

            return output.ToString();
        }

        public static String getXPathSingle(String path) {
            return Regex.Replace(getXPath(path), @"\|$", "");
        }

        public static String getFolder() {
            String path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            return path;
        }

        public static void fillCombo(ComboBox combo, String xpath) {
            String[] items = getXPath(xpath).Split('|');
            combo.Items.Clear();

            for (int i = 0; i < items.Length - 1; i++)
                combo.Items.Add(items[i]);

            if (combo.Items.Count >= 1)
                combo.SelectedIndex = 0;
        }

        public static void fillComboType(ComboBox combo, String xpathType, String xpath, String app) {
            String[] types = getXPath(xpathType).Split('|');
            String[] items = getXPath(xpath).Split('|');

            combo.Items.Clear();

            for (int i = 0; i < items.Length - 1; i++)
                combo.Items.Add(String.Format("{0}{1} - {2}", app, types[i], items[i]));

            if (combo.Items.Count >= 1)
                combo.SelectedIndex = 0;
        }

        public static void fillListType(ListBox list, String xpathType, String xpath, String app) {
            String[] types = getXPath(xpathType).Split('|');
            String[] items = getXPath(xpath).Split('|');

            list.Items.Clear();

            for (int i = 0; i < items.Length - 1; i++)
                list.Items.Add(String.Format("{0}{1} - {2}", app, types[i], items[i]));
        }

        public static int getListIndex(ListBox list, String key) {
            var re = new Regex(String.Format(@"^{0} \- ", key));

            for (int i = 0; i < list.Items.Count; i++) {
                Match m = re.Match(list.Items[i].ToString());

                if (m.Success)
                    return i;
            }

            return -1;
        }

        public static int getComboIndex(ComboBox list, String key) {
            var re = new Regex(String.Format(@"^#?{0}(?: \- )?", key), RegexOptions.IgnoreCase);

            for (int i = 0; i < list.Items.Count; i++) {
                Match m = re.Match(list.Items[i].ToString());

                if (m.Success) {
                    reCheck = false;
                    return i;
                }
            }

            if (!reCheck) {
                reCheck = true;
                int retest = getComboIndex(list, String.Format("'{0}'", key)); //key.Replace("'", String.Empty));

                if (key.IndexOf("'") >= 0 && retest >= 0)
                    return retest;
            }

            MessageBox.Show(String.Format("Key '{0}' not found!", key), "Whoops!", MessageBoxButtons.OK,
                            MessageBoxIcon.Exclamation);

            return -1;
        }

        public static void selectKeys(ListBox list, String keys) {
            String[] all = Regex.Split(keys, "");

            for (int i = 0; i < all.Length; i++) {
                int index = getListIndex(list, all[i]);
                if (index < 0)
                    continue;

                list.SetSelected(index, true);
            }

            if (list.Items.Count >= 1) {
                list.SetSelected(0, !list.GetSelected(0));
                list.SetSelected(0, !list.GetSelected(0));
            }
        }

        public static String getKeys(ListBox list) {
            var sb = new StringBuilder();
            var re = new Regex(@"^(?<key>\w+) \-");

            for (int i = 0; i < list.Items.Count; i++) {
                if (list.GetSelected(i)) {
                    Match m = re.Match(list.Items[i].ToString());

                    sb.Append(m.Groups["key"].Value);
                }
            }

            if (String.IsNullOrEmpty(sb.ToString()))
                return "0";

            return sb.ToString();
        }

        public static String getFlags(ListBox list) {
            var sb = new StringBuilder();

            var re = new Regex(@"(?<flag>\w+) \-");

            for (int i = 0; i < list.SelectedIndices.Count; i++) {
                Match m = re.Match(list.Items[list.SelectedIndices[i]].ToString());

                if (m.Success)
                    sb.Append(m.Groups["flag"].Value);
            }

            return (String.IsNullOrEmpty(sb.ToString()) ? "0" : sb.ToString());
        }

        public static String getComboFlag(ComboBox combo) {
            var re = new Regex(@"\#?(?<flag>'?\-?[\w|\s]*'?)\s*\-?");
            Match m = re.Match(combo.SelectedItem.ToString());

            return (m.Success ? m.Groups["flag"].Value.Trim() : "");
        }
    }
}